package com.hm.common.netty.su;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author shishun.wang
 * @date 下午3:47:10 2017年6月27日
 * @version 1.0
 * @describe
 */
@Sharable // 注解@Sharable可以让它在channels间共享
public class SampleServerHandler extends ChannelInboundHandlerAdapter {

	private static Logger log = LoggerFactory.getLogger(SampleServerHandler.class);

	private ServerCallBack callBack;

	@SuppressWarnings("unused")
	private SampleServerHandler() {

	}

	public SampleServerHandler(ServerCallBack callBack) {
		this.callBack = callBack;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println(ctx.channel().toString());
		for(int i = 0 ; i < 100;i++) {
			ByteBuf buf = (ByteBuf) msg;
			byte[] req = new byte[buf.readableBytes()];
			buf.readBytes(req);
			String body = new String(req, "UTF-8");
			log.info("服务器端接收消息------->" + body);
			String response = callBack.execute(body);
			log.info("服务器端响应消息------->" + response + "[" + body+"]");
			ByteBuf resp = Unpooled.copiedBuffer(response.getBytes());
			ctx.write(resp);
			
			Thread.sleep(500);
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) // flush掉所有写回的数据
				.addListener(ChannelFutureListener.CLOSE); // 当flush完成后关闭channel
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();// 捕捉异常信息
		ctx.close();// 出现异常时关闭channel
	}
}
